using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Tool
{
    public class InteractiveTool
    {
        /// <summary>
        /// byte[]转HexStr
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        /// <summary>
        /// 格式化输入的16进制字符串
        /// </summary>
        /// <param name="str">不带空格的16进制字符串</param>
        /// <param name="totalWidth">16进制规定位数</param>
        /// <returns></returns>
        public static string FormatHexJoint(string str, out bool error, int totalWidth = 2)
        {
            error = false;
            //处理超过总长的字符串
            if (totalWidth < str.Length)
            {
                error = true;
                return null;
            }
            str = str.PadLeft(totalWidth, '0');//给前面填充0
            for (int k = 2; k < str.Length; k += 2)
            {
                str = str.Insert(k, " ");
                k++;
            }
            return str.ToUpper();
        }
        /// <summary>
        /// 把格式化的十六进制字符串转换成Byte数组
        /// </summary>
        /// <param name="InString"></param>
        /// <returns></returns>
        public static byte[] StringToByte(string InString)
        {
            if (InString == string.Empty)
            {
                return new byte[]{ };
            }
            string[] chars = InString.Split(' ');
            
            byte[] outBytes = new byte[chars.Length];
            if (chars.Length >0 )
            {
                for (int i = 0; i < chars.Length; i++)
                {
                    if (chars[i].Length > 2)
                    {
                        if (chars[i].Length % 2 != 0)
                        {
                            chars[i].PadLeft('0');
                        }
                        for (int j = chars[i].Length - 3; j >= 0; j -= 2)
                        {
                            chars[i].Insert(j, " ");
                        }
                    }
                    else
                    {
                        outBytes[i] = Convert.ToByte(chars[i], 16);
                    }
                    
                }
            }
            return outBytes;
        }
    }
}
